# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

from PyQt5.QtCore import (QAbstractItemModel, QDate, QModelIndex, QObject,
                            QStringListModel, Qt, pyqtSlot)
from PyQt5.QtWidgets import (QCompleter, QDateTimeEdit, QLineEdit,
                               QStyleOptionViewItem, QStyledItemDelegate, QWidget)
import logging
# from typing import Optional

class SpreadSheetDelegate(QStyledItemDelegate):

    def createEditor(self, parent: QWidget,
                      option: QStyleOptionViewItem,
                      index: QModelIndex) -> QWidget:
        print("createEditor")
        editor = QLineEdit(parent)
        editor.editingFinished.connect(self.commitAndCloseEditor)
        return editor

    @pyqtSlot()
    def commitAndCloseEditor(self) -> None:
        editor = self.sender()
        self.commitData.emit(editor)
        self.closeEditor.emit(editor)

    def setEditorData(self, editor: QWidget, index: QModelIndex) -> None:
        logging.info("set_editor_data")
        edit = QLineEdit(editor)
        if edit:
            edit.setText(str(index.model().data(index, Qt.EditRole)))
            return

        # dateEditor = QDateTimeEdit(editor)
        # if dateEditor:
        #     dateEditor.setDate(
        #         QDate.fromString(
        #             str(index.model().data(index, Qt.EditRole)), "d/M/yyyy"))

    def setModelData(self, editor: QWidget,
                       model: QAbstractItemModel, index: QModelIndex) -> None:
        logging.info("setModelData")
        logging.info(model)
        edit = QLineEdit(editor)
        if edit:
            model.setData(index, edit.text())
            return

        # dateEditor = QDateTimeEdit(editor)
        # if dateEditor:
        #     model.setData(index, dateEditor.date().toString("dd/M/yyyy"))
